import { defineStore } from 'pinia';
import { 
  traverseDFS, 
  findNode, 
  findParent, 
  getLeafNodes, 
  getNodePath,
  filterTree,
  generateId
} from '../utils/treeUtils.js';

export const useTreeStore = defineStore('tree', {
  state: () => ({
    root: null,
    selectedNodeId: null,
    lastOperation: null,
    operationHistory: [],
    searchTerm: ''
  }),

  getters: {
    // 获取整个树
    tree: (state) => state.root,
    
    // 获取选中的节点
    selectedNode: (state) => {
      return state.root ? findNode(state.root, state.selectedNodeId) : null;
    },
    
    // 获取扁平化的节点列表
    flatNodes: (state) => {
      const nodes = [];
      if (state.root) {
        traverseDFS(state.root, (node) => {
          nodes.push(node);
        });
      }
      return nodes;
    },
    
    // 获取所有叶子节点
    leafNodes: (state) => {
      return state.root ? getLeafNodes(state.root) : [];
    },
    
    // 获取节点数量
    nodeCount: (state) => {
      let count = 0;
      if (state.root) {
        traverseDFS(state.root, () => {
          count++;
        });
      }
      return count;
    },
    
    // 获取树深度
    maxDepth: (state) => {
      let maxDepth = 0;
      if (state.root) {
        traverseDFS(state.root, (node, depth) => {
          if (depth > maxDepth) maxDepth = depth;
        });
      }
      return maxDepth;
    },

    // 过滤后的树
    filteredTree: (state) => {
      if (!state.root || !state.searchTerm) return state.root;
      
      return filterTree(state.root, (node) => 
        node.name.toLowerCase().includes(state.searchTerm.toLowerCase())
      );
    }
  },

  actions: {
    // 初始化树
    initializeTree(rootData = { name: 'Root' }) {
      this.root = {
        id: 'root',
        name: rootData.name,
        data: rootData.data || {},
        parentId: null,
        children: [],
        expanded: true,
        selected: false,
        createdAt: new Date()
      };
      this.addOperation('initialize', { root: this.root });
    },

    // 添加节点
    addNode(parentId, nodeData) {
      if (!this.root) {
        throw new Error('Tree not initialized');
      }

      const parent = findNode(this.root, parentId);
      if (!parent) {
        throw new Error(`Parent node with id ${parentId} not found`);
      }

      const newNode = {
        id: generateId(),
        name: nodeData.name,
        data: nodeData.data || {},
        parentId: parentId,
        children: [],
        expanded: false,
        selected: false,
        createdAt: new Date()
      };

      parent.children.push(newNode);
      this.addOperation('add', { parentId, newNode });
      return newNode;
    },

    // 删除节点
    removeNode(nodeId) {
      if (!this.root) return false;
      
      if (nodeId === this.root.id) {
        throw new Error('Cannot remove root node');
      }

      const parent = findParent(this.root, nodeId);
      if (!parent) return false;

      const nodeIndex = parent.children.findIndex(child => child.id === nodeId);
      if (nodeIndex === -1) return false;

      const [removedNode] = parent.children.splice(nodeIndex, 1);
      
      // 如果删除的是选中的节点，清空选中状态
      if (this.selectedNodeId === nodeId) {
        this.selectedNodeId = null;
      }

      this.addOperation('remove', { parentId: parent.id, removedNode });
      return true;
    },

    // 更新节点
    updateNode(nodeId, updates) {
      const node = findNode(this.root, nodeId);
      if (!node) return false;

      const oldData = { ...node };
      Object.assign(node, updates);
      
      this.addOperation('update', { nodeId, oldData, newData: node });
      return true;
    },

    // 移动节点
    moveNode(nodeId, newParentId) {
      if (nodeId === this.root.id) {
        throw new Error('Cannot move root node');
      }

      const node = findNode(this.root, nodeId);
      const oldParent = findParent(this.root, nodeId);
      const newParent = findNode(this.root, newParentId);

      if (!node || !oldParent || !newParent) {
        throw new Error('Node or parent not found');
      }

      // 从原父节点移除
      const nodeIndex = oldParent.children.findIndex(child => child.id === nodeId);
      const [movedNode] = oldParent.children.splice(nodeIndex, 1);
      
      // 添加到新父节点
      movedNode.parentId = newParentId;
      newParent.children.push(movedNode);

      this.addOperation('move', { 
        nodeId, 
        oldParentId: oldParent.id, 
        newParentId 
      });
      
      return true;
    },

    // 选择节点
    selectNode(nodeId) {
      // 先取消所有节点的选中状态
      if (this.root) {
        traverseDFS(this.root, (node) => {
          node.selected = false;
        });
      }

      const node = findNode(this.root, nodeId);
      if (node) {
        node.selected = true;
        this.selectedNodeId = nodeId;
      } else {
        this.selectedNodeId = null;
      }
    },

    // 切换节点展开状态
    toggleNode(nodeId) {
      const node = findNode(this.root, nodeId);
      if (node) {
        node.expanded = !node.expanded;
      }
    },

    // 展开所有节点
    expandAll() {
      if (this.root) {
        traverseDFS(this.root, (node) => {
          if (node.children.length > 0) {
            node.expanded = true;
          }
        });
      }
    },

    // 折叠所有节点
    collapseAll() {
      if (this.root) {
        traverseDFS(this.root, (node) => {
          node.expanded = false;
        });
      }
    },

    // 查找节点
    findNode(nodeId) {
      return this.root ? findNode(this.root, nodeId) : null;
    },

    // 获取节点路径
    getNodePath(nodeId) {
      return this.root ? getNodePath(this.root, nodeId) : [];
    },

    // 设置搜索条件
    setSearchTerm(term) {
      this.searchTerm = term;
    },

    // 添加操作记录
    addOperation(type, data) {
      const operation = {
        type,
        data,
        timestamp: new Date()
      };
      
      this.operationHistory.push(operation);
      this.lastOperation = operation;
      
      // 保持操作历史在合理范围内
      if (this.operationHistory.length > 50) {
        this.operationHistory.shift();
      }
    },

    // 清空树
    clearTree() {
      this.root = null;
      this.selectedNodeId = null;
      this.searchTerm = '';
      this.addOperation('clear', {});
    },

    // 导入树数据
    importTree(treeData) {
      function createNodeFromData(data, parentId = null) {
        const node = {
          id: data.id,
          name: data.name,
          data: data.data || {},
          parentId,
          children: [],
          expanded: data.expanded || false,
          selected: data.selected || false,
          createdAt: data.createdAt || new Date()
        };
        
        if (data.children && data.children.length > 0) {
          node.children = data.children.map(childData => 
            createNodeFromData(childData, node.id)
          );
        }
        
        return node;
      }
      
      this.root = createNodeFromData(treeData);
      this.addOperation('import', { treeData });
    },

    // 导出树数据
    exportTree() {
      if (!this.root) return null;
      
      function serializeNode(node) {
        return {
          id: node.id,
          name: node.name,
          data: node.data,
          expanded: node.expanded,
          selected: node.selected,
          createdAt: node.createdAt,
          children: node.children.map(serializeNode)
        };
      }
      
      return serializeNode(this.root);
    }
  }
});